package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.common.security.utils.SecurityUtils;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    @Autowired
    private PowerBankMapper powerBankMapper;

    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {
        return powerBankMapper.selectPowerBankList(powerBank);
    }

    @Override
    public int savePowerBank(PowerBank powerBank) {
        // 使用mp 判断编号是否已存在
        long count = count(new LambdaQueryWrapper<PowerBank>()
                .eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));

        if (count>0){
            throw new ServiceException("该充电宝编号已存在");
        }

        powerBank.setCreateBy(SecurityUtils.getUsername()); //设置操作人 当前登录用户
        powerBank.setUpdateBy(SecurityUtils.getUsername());
        powerBank.setUpdateTime(new Date());
        return powerBankMapper.insert(powerBank);
    }

    //修改充电宝
    @Override
    public int updatePowerBank(PowerBank powerBank) {
        //判断充电宝是否已投放 未投放才可以修改 为0
        PowerBank pb = powerBankMapper.selectById(powerBank.getId());
        if (!pb.getStatus().equals("0")){
            throw new ServiceException("充电宝已投入使用，无法修改");
        }

        //判断充电宝编号是否重复
        Wrapper<PowerBank> wrapper = new LambdaQueryWrapper<PowerBank>()
                .eq(PowerBank::getPowerBankNo,powerBank.getPowerBankNo());
        Long count = powerBankMapper.selectCount(wrapper);
        if (count>0) throw new ServiceException("充电宝编号已存在，请重新输入");

        //设置修改者 时间等
        powerBank.setUpdateBy(SecurityUtils.getUsername());
        powerBank.setUpdateTime(new Date());

        return powerBankMapper.updateById(powerBank);
    }

    //根据充电宝编号查询充电宝
    @Override
    public PowerBank getByPowerBankNo(String powerBankNo) {
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PowerBank::getPowerBankNo,powerBankNo); //充电宝编号

        PowerBank powerBank = powerBankMapper.selectOne(wrapper);

        return powerBank;
    }
}
